// pages/appointment-list/appointment-list.js
const app = getApp();
const util = require('../../utils/util.js');

Page({
  data: {
    appointmentList: [],
    searchKeyword: '',
    searchStatus: ''
  },

  onLoad() {
    this.loadAppointmentList();
  },

  onShow() {
    this.loadAppointmentList();
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索
  handleSearch() {
    this.loadAppointmentList();
  },

  // 按状态筛选
  filterByStatus(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      searchStatus: status
    });
    this.loadAppointmentList();
  },

  loadAppointmentList() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      return;
    }

    app.showLoading();
    
    const data = {
      userId: userInfo.id,
      page: 1,
      size: 100
    };
    
    // 添加搜索条件
    if (this.data.searchKeyword) {
      data.hospitalName = this.data.searchKeyword;
    }
    if (this.data.searchStatus) {
      data.status = this.data.searchStatus;
    }

    app.request({
      url: '/appointment/list',
      method: 'GET',
      data: data
    }).then(res => {
      if (res.success) {
        // 格式化数据
        const appointmentList = (res.data.records || []).map(item => {
          return {
            ...item,
            appointmentDate: util.formatDate(item.appointmentDate),
            createTime: util.formatDateTime(item.createTime),
            images: item.images ? item.images.split(',').filter(img => img.trim()) : []
          };
        });
        this.setData({
          appointmentList: appointmentList
        });
      }
    }).catch(err => {
      app.showToast('加载失败');
      console.error(err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  // 预览图片
  previewImage(e) {
    const images = e.currentTarget.dataset.images;
    const current = e.currentTarget.dataset.current;
    wx.previewImage({
      urls: images,
      current: current
    });
  },

  // 上报到店
  reportArrival(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确认已到店吗？',
      success: (res) => {
        if (res.confirm) {
          this.performReportArrival(id);
        }
      }
    });
  },

  // 执行上报到店
  performReportArrival(id) {
    app.showLoading('上报中...');
    app.request({
      url: `/appointment/updateStatus?id=${id}&status=已到店`,
      method: 'POST'
    }).then(res => {
      if (res.success) {
        wx.showToast({
          title: '上报到店成功',
          icon: 'success'
        });
        // 刷新列表
        this.loadAppointmentList();
      } else {
        app.showToast(res.message || '上报失败');
      }
    }).catch(err => {
      app.showToast('上报失败，请稍后重试');
      console.error('上报到店失败', err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  // 取消预约
  cancelAppointment(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要取消该预约吗？',
      success: (res) => {
        if (res.confirm) {
          this.performCancelAppointment(id);
        }
      }
    });
  },

  // 执行取消预约
  performCancelAppointment(id) {
    app.showLoading('取消中...');
    app.request({
      url: `/appointment/cancel/${id}`,
      method: 'POST'
    }).then(res => {
      if (res.success) {
        wx.showToast({
          title: '已取消预约',
          icon: 'success'
        });
        // 刷新列表
        this.loadAppointmentList();
      } else {
        app.showToast(res.message || '取消失败');
      }
    }).catch(err => {
      app.showToast('取消失败，请稍后重试');
      console.error('取消预约失败', err);
    }).finally(() => {
      app.hideLoading();
    });
  }
});


